package handlers

import (
	"github.com/gin-gonic/gin"
	"quiz-master/cache"
	"quiz-master/model"
	"quiz-master/pkg"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}

func List1(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT *
		from roles
		LEFT JOIN user_roles on user_roles.rid=roles.id
		WHERE user_roles.uid =1
	*/
	var roles []model.Role
	model.DB.
		Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid = ?", uid).Find(&roles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"user": roles,
	})
	return
}

func UserNodeList1(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT *
		from nodes
		LEFT JOIN role_nodes on nodes.id=role_nodes.nid
		WHERE role_nodes.rid =1
	*/
	var nodes []model.Node
	model.DB.
		Table("nodes").
		Joins("LEFT JOIN role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid = ?", rid).Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"user": nodes,
	})
	return
}
